package com.kaifamiao.dao.impl;

import com.kaifamiao.dao.UserDAO;
import com.kaifamiao.domain.User;
import com.kaifamiao.exception.DaoException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;
import java.util.List;

@Repository
public class UserDaoByJdbc implements UserDAO {

    @Autowired
    private JdbcTemplate template;

    @Override
    public User find(Integer id) throws DaoException {
        return null;
    }

    @Override
    public List<User> findAll(Integer id) throws DaoException {
        return null;
    }

    @Override
    public int persist(User user) throws DaoException {
        String sql = "INSERT INTO t_users " +
                     "(account, email, tel, password, salt, nickname, gender, birthdate, married, admin) " +
                     "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        PreparedStatementCreator psc = new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                // 创建PreparedStatement实例并指示需要获取由数据库生成的主键
                PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                // 依次设置参数占位符的值
                ps.setString( 1, user.getAccount() );
                ps.setString( 2, user.getEmail() );
                ps.setString( 3, user.getTel() );
                ps.setString( 4, user.getPassword() );
                ps.setString( 5, user.getSalt() );
                ps.setString( 6, user.getNickname() );
                ps.setInt( 7, user.getGender().ordinal() );
                LocalDate birthdate = user.getBirthdate();
                java.sql.Date date = birthdate == null ? null : java.sql.Date.valueOf( birthdate );
                ps.setDate( 8, date );
                ps.setString( 9, user.isMarried() ? "Y" : "N");
                ps.setString( 10, user.isAdmin() ? "Y" : "N");
                return ps;
            }
        };

        KeyHolder holder = new GeneratedKeyHolder();

        try {
            int id = template.update(psc, holder);
            user.setId(id);
            return id;
        } catch ( DataAccessException dae ) {
            throw new DaoException( dae );
        }
    }

    @Override
    public int update(User user) throws DaoException {
        return 0;
    }

    @Override
    public int remove(Integer id) throws DaoException {
        return 0;
    }

}
